using B.S.RbacData.ErrorCode;
using ContentmanagementBaseWrite.API.Applications.Commands;
using ContentmanagementBaseWrite.API.Services;
using MediatR;

namespace ContentmanagementBaseWrite.API.Applications.Commandhandlters
{
    /// <summary>
    /// 上传图片命令处理器
    /// </summary>
    public class UploadImageCommandHandler : IRequestHandler<UploadImageCommand, ApiResult<string>>
    {
        private readonly IMinioService _minioService;
        private readonly ILogger<UploadImageCommandHandler> _logger;

        public UploadImageCommandHandler(IMinioService minioService, ILogger<UploadImageCommandHandler> logger)
        {
            _minioService = minioService;
            _logger = logger;
        }

        /// <summary>
        /// 处理上传图片命令
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>上传结果</returns>
        public async Task<ApiResult<string>> Handle(UploadImageCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始处理图片上传命令，文件名：{FileName}，存储桶：{BucketName}", 
                    request.ImageFile.FileName, request.BucketName);

                // 验证文件
                if (request.ImageFile == null || request.ImageFile.Length == 0)
                {
                    _logger.LogWarning("上传的文件为空或无效");
                    return new ApiResult<string>
                    {
                        code = ResultEnumCode.fails,
                        message = "上传的文件为空或无效",
                        data = string.Empty
                    };
                }

                // 验证文件类型
                var allowedExtensions = new[] { ".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp" };
                var fileExtension = Path.GetExtension(request.ImageFile.FileName).ToLowerInvariant();
                
                if (!allowedExtensions.Contains(fileExtension))
                {
                    _logger.LogWarning("不支持的文件类型：{FileExtension}", fileExtension);
                    return new ApiResult<string>
                    {
                        code = ResultEnumCode.fails,
                        message = $"不支持的文件类型：{fileExtension}，支持的格式：{string.Join(", ", allowedExtensions)}",
                        data = string.Empty
                    };
                }

                // 验证文件大小（默认限制为10MB）
                var maxFileSize = 10 * 1024 * 1024; // 10MB
                if (request.ImageFile.Length > maxFileSize)
                {
                    _logger.LogWarning("文件大小超过限制：{FileSize} bytes，最大允许：{MaxFileSize} bytes", 
                        request.ImageFile.Length, maxFileSize);
                    return new ApiResult<string>
                    {
                        code = ResultEnumCode.fails,
                        message = $"文件大小超过限制，最大允许：{maxFileSize / 1024 / 1024}MB",
                        data = string.Empty
                    };
                }

                // 生成对象名称
                string objectName;
                if (request.GenerateUniqueName)
                {
                    var uniqueFileName = MinioService.GenerateUniqueFileName(request.ImageFile.FileName);
                    objectName = $"{request.Prefix}/{uniqueFileName}";
                }
                else
                {
                    objectName = $"{request.Prefix}/{request.ImageFile.FileName}";
                }

                _logger.LogDebug("生成的对象名称：{ObjectName}", objectName);

                // 上传文件到MinIO
                var imageUrl = await _minioService.UploadFileAsync(request.ImageFile, request.BucketName, objectName);

                _logger.LogInformation("图片上传成功，访问URL：{ImageUrl}", imageUrl);

                return new ApiResult<string>
                {
                    code = ResultEnumCode.Ok,
                    message = "图片上传成功",
                    data = imageUrl
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "图片上传过程中发生异常，文件名：{FileName}", request.ImageFile?.FileName);
                
                return new ApiResult<string>
                {
                    code = ResultEnumCode.fails,
                    message = $"图片上传失败：{ex.Message}",
                    data = string.Empty
                };
            }
        }
    }
} 